﻿using CQRSFramework.Common.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace CQRSFramework.Domains.Impl
{
    public class AggregateFactory : IAggregateFactory
    {
        public T CreateAggregate<T>() where T : IAggregateRoot
        {
            var constructorInfos = typeof(T).GetConstructors().ToList();
            if (constructorInfos.Count() > 1)
            {
                throw new Exception("");
            }
            var constructorInfo = constructorInfos.SingleOrDefault();
            var parameterInfos = constructorInfo.GetParameters();
            object[] parameters = new object[parameterInfos.Count()];
            foreach (var parameter in parameterInfos)
            {
                parameters[parameter.Position] = ObjectContainer.ResolveOptional(parameter.GetType());
            }
            return (T)Activator.CreateInstance(typeof(T), parameters);
        }

        /// <summary>
        /// 不调用构造函数实例化一个对像
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type"></param>
        /// <returns></returns>
        public T CreateAggregate<T>(Type type) where T : IAggregateRoot
        {
            return (T)System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof(T));
        }
    }
}
